using System.Reflection;
using EPiServer.Core;

namespace EPiSugar.EntityAdapter.PropertyBinders
{
    public class ReferenceBinder : PropertyBinder
    {
        public ReferenceBinder(string sourceProperty, PropertyInfo destinationProperty)
            : base(sourceProperty, destinationProperty)
        {
        }

        protected override void SetValue(object instance, object value)
        {
            PageReference pageLink = value as PageReference;
            if(pageLink != null)
            {
                PageData page = Current.PageSource.GetPage(pageLink);
                object entity = Current.Model.GetEntity(page);
                DestinationProperty.SetValue(instance, entity, NoParameters);
            }
        }
    }
}